//
//  XJPageContentView.swift
//  XJZB
//
//  Created by 李胜兵 on 16/9/25.
//  Copyright © 2016年 付公司. All rights reserved.



/**
  问题一:强引用外界的控制器以后，要么给里面变量增加weak private weak var parentViewController : UIViewController?
  使用⚠️：parentViewController?.addChildViewController(childVc)


  问题二:懒加载里面如果到了self，懒加载其实就是一个闭包，最好不要使用self，修改如下：[weak self] in

  问题三:就是外面HomeViewController中传入的self，也需要在闭包中和问题二一样这样做，然后我们构造函数需要修改传入一个可选类型就可以了

  */

import UIKit

protocol XJPageContentViewDelegate : class {
    func xjPageContentView(_ contentView : XJPageContentView , progress : CGFloat , sourceIndex : Int , targetIndex : Int)
}


private let contentCellID = "contentCellID"

class XJPageContentView: UIView {

    // MARK: - 定义属性保存传来的参数
    fileprivate var childVcs : [UIViewController]
    fileprivate weak var parentViewController : UIViewController?
    fileprivate var starOffsetX : CGFloat = 0
    weak var delegate : XJPageContentViewDelegate?
    // 静止点击的时候代理出发让外界方法执行
    fileprivate var isForbidScrollDelegate : Bool = false
    
    // MARK: - 懒加载collectionView
    fileprivate lazy var collectionView : UICollectionView = {[weak self] in
        
        // 1.创建layout
        let layout = UICollectionViewFlowLayout()
        layout.itemSize = (self?.bounds.size)!
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        layout.scrollDirection = .horizontal
        
        // 2.创建UICollectionView
        let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.isPagingEnabled = true
        collectionView.bounces = false
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.backgroundColor = XJColorDefault
        
        // 注册cell
        collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: contentCellID)
        return collectionView
    }()
    
    // MARK: - 自定义构造函数
    init(frame: CGRect , childVcs : [UIViewController] , parentViewController : UIViewController?) {
        self.childVcs = childVcs
        self.parentViewController = parentViewController
        super.init(frame: frame)
        // 设置UI
        setupUI()
    }
    
    // MARK: - 自定义构造函数必须要实现的方法
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}


// MARK: - 设置UI界面
extension XJPageContentView {
    fileprivate func setupUI() {
       // 1.将所有子控制器加到父控制器中
        for childVc in childVcs {
            parentViewController?.addChildViewController(childVc)
        }
        
        // 2.添加UICollectionView，用于在cell中存放控制器的view
        addSubview(collectionView)
        collectionView.frame = bounds
    }
}


// MARK: - collectionView数据源方法
extension XJPageContentView : UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return childVcs.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        // 1.创建cell
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: contentCellID, for: indexPath)
        
        // 2.给cell设置内容
        // 2.1cell有循环复用的问题，为了防止复用，我们每次添加之前先移除之前的view
        for view in cell.contentView.subviews {
            view.removeFromSuperview()
        }
        
        let childVc = childVcs[(indexPath as NSIndexPath).item]
        childVc.view.frame = cell.contentView.bounds
        cell.contentView.addSubview(childVc.view)
        
        return cell
    }
}


// MARK: - collectionView代理方法
extension XJPageContentView : UICollectionViewDelegate {
    
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        
        // 代理不禁止执行
        isForbidScrollDelegate = false
        
        starOffsetX = scrollView.contentOffset.x;
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        // 判断是否是点击事件还是滚动事件
        if isForbidScrollDelegate { return }

        // 1.获取所需要的数据<(progress)+(sourceIndex)+(targetIndex)>
        // 1.0定义所需的数据
        var progress : CGFloat = 0
        var sourceIndex : Int = 0
        var targetIndex : Int = 0
        
        // 2.判断是左滑还是右滑
        let curentOffsetX = scrollView.contentOffset.x
        let scrollViewWidth = scrollView.bounds.width
        if  curentOffsetX > starOffsetX {  // 左滑动
            // 2.0计算进度
            progress = curentOffsetX / scrollViewWidth - floor(curentOffsetX / scrollViewWidth)
            
            // 2.1计算sourceIndex
            sourceIndex = Int(curentOffsetX / scrollViewWidth)
            
            // 2.2计算targetIndex
            targetIndex = sourceIndex + 1
            if targetIndex >= childVcs.count {
                targetIndex = childVcs.count - 1
            }
            
            // 2.3如果完全滑动过去，progress应该为1
            if curentOffsetX - starOffsetX == scrollViewWidth {
                progress = 1
                targetIndex = sourceIndex
            }
        }else { // 右滑动
            
            // 2.00
            progress = 1 - (curentOffsetX / scrollViewWidth - floor(curentOffsetX / scrollViewWidth))
            
            // 2.11计算targetIndex
            targetIndex = Int(curentOffsetX / scrollViewWidth)
            
            // 2.22计算sourceIndex
            sourceIndex = targetIndex + 1
            if sourceIndex >= childVcs.count {
                sourceIndex = childVcs.count - 1
            }
        }
        
        
        
        // 3.将(progress)+(sourceIndex)+(targetIndex)传递给titleView
        
        //print("progress:\(progress) - sourceIndex:\(sourceIndex) - targetIndex:\(targetIndex)")
        delegate?.xjPageContentView(self, progress: progress, sourceIndex: sourceIndex, targetIndex: targetIndex)
        
    }
}


// MARK: - 暴露外界一个方法
extension XJPageContentView {
    func setCurrentIndex(_ currentIndex : Int) {
        
        // 1.纪录需要执行的代理方法
        isForbidScrollDelegate = true
        
        let offsetX =  CGFloat(currentIndex) * collectionView.frame.width
        collectionView.setContentOffset(CGPoint(x: offsetX, y: 0), animated: false)
    }
}









